// packageC/pages/Craftsman/Craftsman.js
const common = require('../../../public.js')
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        value: 4.5,
        numms: 3,//展开更多
        tabList: [
            { tabName: '产品', samllName: '强烈推荐' },
            { tabName: '评价', samllName: '99+条评论' },
            { tabName: '商家', samllName: '查看信息' },
        ],
        ClassificationList: [
            '全部分类',
            '分类一',
            '分类二',
        ],
        actiiveClass: -1,
        actiiveIndex: 0,
        showCoupFlag: false,
        storeCouponsList:[]
    },

    receiveStoreConpons(e) {
        let that = this
        console.log(e,"kikikiiiiiiii")
        let couponid = e.detail.id.couponid
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }
        common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
                that.setData({
                    storeCouponsList: []
                }, () => {
                    that.getStoreCoupons(that.data.storeId, true)
                })

            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },

    // 店铺优惠券列表
    getStoreCoupons(refresh = true) {
        const that = this
        if (refresh) {
            this.data.canLoad = true
        }
        if (that.data.canLoad) {  //可以加载
            if (!refresh && this.data.isLoadingBusy) {
                return
            }
            this.setData({
                isLoadingBusy: true
            })
            const params = {
                storeId: that.data.storeId,
                pageNum: refresh ? 1 : that.data.pageNum + 1,
                status: 4
            }
            common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
                if (res.status === 200) {
                    that.data.pageNum = params.pageNum
                    if (res.data.result_list != '' || res.data.result_list.length != 0) {
                        that.setData({
                            storeCouponsList: [...that.data.storeCouponsList, ...res.data.result_list],
                        })
                    } else {
                        if (that.data.pageNum == 1) {
                            that.setData({
                                storeCouponsList: []
                            })
                            return
                        }
                        that.setData({
                            canLoad: false,
                        })
                    }

                }
            }, function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
        }

    },

    // 列表触底
    loadMore() {
        this.getStoreCoupons(false)
    },
    purchase(e) {
        var that = this
       
        let id = e.currentTarget.dataset.item.id
        if (that.data.isVip && that.data.code == '') { // 是vip商品且用户不是手艺人
          that.setData({
            showVip: true
          })
        } else {
            app.globalData.cardId = '';
            app.globalData.discount = 1
            app.globalData.productprice = ''
          wx.navigateTo({
            url: '/packageA/pages/Goods/Commit/index?itemId=' + id + '&storeId=' + that.data.storeId,
          })
        }
      },
    goodsDetail(e) {
        common.gotoGoodsPage(e.currentTarget.dataset.item)
    },
    click_actiiveClass(e) {
        const that = this
        let index = e.currentTarget.dataset.index
        const idx = e.currentTarget.dataset.id
        this.setData({
            actiiveClass: index
        })
        that.changeCategory(idx)


    },
    click_total() {
        this.setData({
            defaultItemList: this.data.totalDefaultItemList
        })
    },
    // tabs点击
    click_tabs(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actiiveIndex: index
        },()=>{
            console.log(this.data.actiiveIndex,"4444477777")
        })
    },
    changeCategory(idx) {
        this.setData({
            isLoading: true
        })
        const that = this
        const tempJson = {
            cid: idx,
            storeId: that.data.storeId,
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        common.post('/store/mainPageInfo/cid', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    defaultItemList: res.data.data
                })
            } else {
                that.setData({
                    defaultItemList: []
                })
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },

    //    立即结算
    go_balance(e) {
        console.log(e)
        // this.submitAddCart(e)
    },
    // 添加购物车
    submitAddCart(e) {

        const that = this
        const num = 1
        const itemId = e.currentTarget.dataset.item.id
        const price = e.currentTarget.dataset.item.price

        let tempJson = {
            dishFlavor: that.data.checkedAttr,
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId,
            num
        }
        common.wxRequest('/cart/add', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                wx.navigateTo({
                    url: `/packageC/pages/takeoutOrder/takeoutOrder?storeId=${that.data.storeId}&totalPrice=${price}`,
                })
            } else {

            }
        })
    },
    // 电话
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopInfo.store.mobile,
            fail: function () { }
        })
    },
    checkAddress() { //点击地址按钮
        if (!this.data.shopInfo.store.xpoint || !this.data.shopInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.shopInfo.store.xpoint)
        let lat = parseFloat(this.data.shopInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.shopInfo.store.name ? this.data.shopInfo.store.name : null,
            address: this.data.shopInfo.store.address ? this.data.shopInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 触底效果
    fnLower(e) {
        this.gong(false)
    },
    gong(refresh = false) {
        const that = this
        if (this.data.isLoadingBusy) {
            return
        }
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        let tempJson = {
            pageSize: 10,
            pageNum,
            storeId: this.data.storeId
        }
        common.post('/storeArticle/getStoreArticleListForOneStore', tempJson,
            function (res) {
                if (res.data) {
                    for (let i = 0; i < res.data.list.length; i++) {
                        let item = res.data.list[i]
                        let goodsRemark = item.content.replace(/\<img/gi, '<img style="display:none"');
                        res.data.list[i].content = goodsRemark
                    }
                }

                that.data.pageNum = pageNum
                if (res.status === 200) {
                    that.setData({
                        articleList: res.data.list,
                        articleLists: refresh ? res.data.list : [...res.data.list, ...that.data.articleLists]
                    }, () => {
                        that.stopFn(res)
                    })
                } else {
                    // common.showRequestErrMsg(res)
                    that.stopFn(res)
                }
            },
            function () {
                // that.setData({
                //     isLoadingBusy: false
                // })
            })
    },
    // 没有数据不掉接口
    stopFn(res) {
        const that = this
        if (res.data && res.data.list !== []) {
        } else {
            that.setData({
                isLoadingBusy: true
            })
        }
    },
    // 图片预览
    preview(event) {
        let { nindex, windex } = event.currentTarget.dataset
        console.log(nindex, windex)
        let pic_ce = this.data.commentList[windex].picUrls
        this.setData({
            pic_ce,
            current: nindex,
            showImg: true
        })
    },
    goDetails(e) {
        let itemId = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: `/packageC/pages/takeoutDetail/takeoutDetail?itemId=${itemId}&storeId=${this.data.storeId}`,
        })

    },
    // 获取购物车数量
    getCartNum(flag = false) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/listByStore', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                let totalPrice = 0;
                let totalNum = res.data.totalNum
                res.data.list.map((item, index) => {
                    totalPrice = item.num * item.price + totalPrice
                })
                // console.log(res.data.totalNum,"44475665555")

                that.setData({
                    cartList: res.data.list,
                    cartNum: totalNum,
                    goodsCount: 1,
                    totalPrice
                })

            } else {
                that.setData({
                    cartList: [],
                    cartNum: 0,
                    goodsCount: 1,
                    totalPrice: 0
                })
                // if (!flag) {
                //     wx.showToast({
                //         icon: 'none',
                //         title: res.msg ? res.msg : '添加失败',
                //     })
                // }

            }
        }, () => {
            if (that.data.cartNum >= 1) {
                that.clearCart()
            }
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 店铺详情
    shopInfo() {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            xcFlag: '0' //是否含有携程门票 0不含有
        }
        common.get('/store/mainPageInfo', tempJson, res => {
            for (let i = 0; i < res.data.couponList.length; i++) {
                that.setData({
                    industryType: res.data.store.industryType
                })
            }
            console.log(res.data.commentList,"res.data.commentListres.data.commentList")
            if (res.data.commentList) {
                for (var i = 0; i < res.data.commentList.length; i++) {
                    res.data.commentList[i].addTime = that.time(res.data.commentList[i].addTime)
                }
                that.data.tabList[1].samllName = `${res.data.commentList.length}条评论`
            }else{
                that.data.tabList[1].samllName = `暂无评论`
            }
           
            // console.log(that.data.tabList,"pppppppppppppppppp")
            that.setData({
                tabList: that.data.tabList,
                totalCommentList: res.data.commentList,
                cateLeftList: res.data.itemCatList2.storeCatList,
                activeId: res.data.itemCatList2.storeCatList.length > 0 ? res.data.itemCatList2.storeCatList[0].id : '',
                couponList: res.data.couponList,
                shopInfo: res.data,
                totalDefaultItemList: res.data.itemCatList2.defaultItemList
                // defaultItemList: res.data.itemCatList2.defaultItemList,
            }, () => {
                // 计算右侧商品高度
                var defaultItemList = that.lengthArray(res.data.itemCatList2.defaultItemList, that.data.numms)
                // var commentList = that.lengthArray(res.data.commentList, 2)

                that.setData({
                    defaultItemList,
                    // commentList
                })

            })
        })
    },
    // 评价
    click_comment() {
        this.setData({
            commentList: this.data.totalCommentList
        })
    },
    click_total() {
        this.setData({
            defaultItemList: this.data.totalDefaultItemList
        })
    },
    // 数组截取
    lengthArray(arr, num) {
        if (arr.length > num) {
            arr = arr.slice(0, num)
        }
        return arr
    },
    toArticleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/discovery/articleDetail/index?id=' + item.id +
                '&storeName=' + item.storeName +
                '&title=' + item.title +
                '&createTime=' + item.createTime +
                '&storeImg=' + item.storeImg
        })
    },

    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                isCollected: res.data
            })
        });
    },
    // 是否收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })
    },

    // 商品接口
    changeCategory(idx) {
        this.setData({
            isLoading: true
        })
        const that = this
        const tempJson = {
            storeCid: idx,
            storeId: that.data.storeId,
            token: that.data.token,
            userId: that.data.userInfo.id
        }
        common.post('/store/mainPageInfo/storeCid', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    defaultItemList: res.data.data
                }, () => {

                })
            } else {
                that.setData({
                    defaultItemList: []
                })
                common.showRequestErrMsg(res)
            }
        }, function () {
            that.setData({
                isLoading: false
            })
        })
    },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    click_coup() {
        this.setData({
            showCoupFlag: true
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // let winHeight = (res.windowHeight - 10 - 40) * 750 / res.screenWidth
    
        const that = this
        this.setData({
            toView: 'a1',
        })
        // 返回按钮
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
          
            height: capsule.height,
            top: capsule.top,
            storeId: options.id ? options.id : 2182,

        })
        // 用户信息
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.setData({
                    userInfo: data.user,
                    token: data.token,
                    openid: data.openid,
                }, () => {
                    this.clickCollect()  //是否收藏
                    // this.getCartNum(true)
                    this.gong(true)
                    this.queryCollection()
                    this.getStoreCoupons(true)
                   
                })
            }
        }, true)

        // 定位
        that.getLocation()
    },
    onShow(){
       
    },
    // 获取当前定位
    getLocation() {
        app.getLocation(
            (data) => {
                this.setData({
                    lon: data.longitude,
                    lat: data.latitude
                }, () => {
                    this.shopInfo()
                })
            },
            (err) => {
                // 定位失败回调
                this.setData({
                    refreshing: false
                })
            })
    },
    // 右侧商品的高度
    heightArry(res) {
        let h = 0;
        let heightArr = [];
        res[0].forEach((item) => {
            h += item.height;
            heightArr.push(h);
        })
        this.setData({ heightArr: heightArr })
    },
    // 滚动事件
    Right_Scroll(e) {
        const that = this
        if (!that.data.clickShow) {
            let scrollHeight = e.detail.scrollTop;
            let index = this.calculateIndex(this.data.heightArr, scrollHeight);
            console.log(index)
            this.setData({
                activeId: this.data.defaultItemList[index].storeCid
            }, () => {
            })
        }
        this.setData({
            clickShow: false
        })

    },
    // 计算左边选中的下标
    calculateIndex(arr, scrollHeight) {
        let index = '';
        for (let i = 0; i < arr.length; i++) {
            if (scrollHeight >= 0 && scrollHeight < arr[0]) {
                index = 0;
            } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                index = i;
            }
        }
        return index;
    },
    // 二级分类点击
    clickItem(e) {
        const that = this
        this.setData({
            activeId: e.currentTarget.dataset.id,
            toView: e.currentTarget.dataset.id,
            clickShow: true
        }, () => {

            // that.changeCategory(e.currentTarget.dataset.id)
            //    const index =  that.data.defaultItemList.findIndex((i)=>{
            //          return i.storeCid === this.data.activeId
            //     })
            //     console.log(index)
            //     console.log(this.data.heightArr)
        })
    },
    // tabs切换
    click_item(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIndex: index
        })
    },
    // 点击收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })

    },
    // 选规格
    go_guige() {
        this.setData({
            guigeShow: true
        })
    },
    onClose() {
        this.setData({
            guigeShow: false
        });
    },
    // 商品规格
    clickGetDishAttrList(e) {
        let that = this
        let { id, item } = e.currentTarget.dataset
        let tempJson = {
            itemId: id,

        }
        that.setData({
            itemId: id,
            goodsNei: item
        })
        common.post("/item/getDishAttrList", tempJson, function (res) {
            let checkedStr = '';

            for (let i = 0; i < res.data.length; i++) {
                if (i !== res.data.length - 1) {
                    checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
                } else {
                    checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
                }

            }

            that.setData({
                attrValueList: res.data,
                checkedAttr: checkedStr
            })
        })
    },
    clickGoodsCount(e) {
        this.setData({
            goodsCount: e.detail,
        }, () => {
            // this.submitAddCart()
        })
    },

    closeAddCart() {
        this.setData({
            guigeShow: false
        })
    },
    // 点击购物车
    click_shoppcar() {
        this.setData({
            shopCarShow: true
        }, () => {
            this.getCartNum()
        })
    },
    // 清空购物车    userId  cartIds  删除或者多个
    clearCart() {
        const that = this
        let arrList = []
        for (let i = 0; i < that.data.cartList.length; i++) {
            arrList.push(that.data.cartList[i].id)
        }

        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartIds: arrList.toString(),
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/deleteByCartId ', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                // that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 返回上页面
    goBack() {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 购物车关闭
    onCloses() {
        this.setData({
            shopCarShow: false
        })
    },
    //购物车减少一
    onminus(e) {
        let item = e.currentTarget.dataset.item
        let cartId = item.id
        console.log(item, "lllllllllllllllllllllllllllllllllllllll")
        this.changeCartNum(-1, cartId, item.itemId)

    },
    //  购物车增加1
    onplus(e) {
        let { index, item } = e.currentTarget.dataset
        let cartId = item.id
        this.changeCartNum(1, cartId, item.itemId)
    },
    //购物车加一
    changeCartNum(num, cartId, itemId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: itemId,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest('/cart/updateOneByCartId', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 购物车输入改变
    onblur(e) {
        const that = this
        let { item } = e.currentTarget.dataset
        let num = e.detail.value
        let cartId = item.id
        that.inputCartNum(num, cartId, item.itemId)

    },
    //  输入input改变     userId cartId num   修改数量
    inputCartNum(num, cartId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartId,
            num,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/updateNumByCartId', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },

})